<template>
  <a-card :bordered="false">
    <Header :title="'返回'" :subTitle="'明细管理'" :hasBackPath="true" @headerBack="$router.back()"></Header>
    <RecordFilter
      ref="recordFilter"
      :sendType="details.sendType"
      :pageId="$route.params.id"
      :selectedRowKeys="selectedRowKeys"
      @onReissueLog="handleReissueLog"
      @onReissueCoupon="onReissueCoupon"
      @handleExportSendPageInfoByPageId="handleExportSendPageInfoByPageId"
      @onSearch="onSearch"></RecordFilter>
    <a-descriptions title="通用信息" :column="4">
      <a-descriptions-item label="批次号">
        {{details.id}}
      </a-descriptions-item>
      <a-descriptions-item label="最小券号">
        {{details.smallNo}}
      </a-descriptions-item>
      <a-descriptions-item label="最大券号">
        {{details.bigNo}}
      </a-descriptions-item>
      <a-descriptions-item label="领用部门">
        {{details.department}}
      </a-descriptions-item>
      <a-descriptions-item label="发券类型">
        <!-- 发券类型1微信券2礼券3纸质券 -->
        <template v-if="details.sendType == 1">微信券</template>
        <template v-if="details.sendType == 2">礼券</template>
        <template v-if="details.sendType == 3">纸质券</template>
      </a-descriptions-item>
      <a-descriptions-item label="领用券总金额">
        {{details.totalAmount}}
      </a-descriptions-item>
      <a-descriptions-item label="领用券总数量">
        {{details.totalNum}}
      </a-descriptions-item>
      <a-descriptions-item label="申请理由">
        {{details.remarks}}
      </a-descriptions-item>
    </a-descriptions>
    <s-table
      ref="table"
      size="default"
      :rowKey="(record,index)=> record.vouNo"
      :columns="columns"
      :data="loadData"
      :pagination="paginationProps"
      :scroll="{ x: 1300 }"
      :rowSelection="rowSelection"
    >
      <span slot="sendType" slot-scope="record">
        <span v-if="details.sendType == 1">微信券</span>
        <span v-if="details.sendType == 2">礼券</span>
        <span v-if="details.sendType == 3">纸质券</span>
      </span>
      <span slot="status" slot-scope="record">
        <span v-if="record.status === 0">正常</span>
        <span v-if="record.status == 1">核销</span>
        <span v-if="record.status == 2">失效</span>
        <span v-if="record.status == 3">作废</span>
      </span>
      <span slot="action" slot-scope="record">
        <a v-if="record.status === 0 || record.status == 2" @click="handleOpenDelay(record)">延期</a>
        <a v-else style="color: #dadada;">延期</a>
        <template v-if="details.sendType != 1">
          <a-divider type="vertical" />
          <a v-if="record.status === 0" @click="handlePrint(record)">补打印</a>
          <a v-else style="color: #dadada;">补打印</a>
        </template>
        <a-divider type="vertical"/>
        <a  v-if="record.status === 0" @click="handleOpenCancel(record)">作废</a>
        <a v-else style="color: #dadada;">作废</a>
        <a-divider v-if="record.vouNo" type="vertical"/>
        <a @click="handleOpenCouponLog(record.vouNo)" v-if="record.vouNo">日志</a>
      </span>
    </s-table>
    <div class="batch-operation-wrapper" v-if="records.length">
      <a style="margin-left: 14px;" @click="onSelectAll">全{{selectedRowKeys.length == records.length ? '不' : ''}}选</a>
      <a-button :disabled="!selectedRowKeys.length" style="margin-left: 8px" @click="handleOpenBatchDelay">优惠券延期</a-button>
      <a-button :disabled="!selectedRowKeys.length" v-if="details.sendType == 2 || details.sendType == 3" style="margin-left: 8px" @click="handleBatchPrint">优惠券补打印</a-button>
      <a-button :disabled="!selectedRowKeys.length" style="margin-left: 8px" @click="handleOpenBatchCancel">优惠券作废</a-button>
    </div>
    <LogModal :title="logTitle" :visible.sync="visibleLog" :pagination.sync="logPagination" :data="logData" @onPageChange="onPageChange"></LogModal>
    <CommonModal :type="1" :visible.sync="visibleDelay" @onCommonModalOk="handleVoucherDelay"></CommonModal>
    <CommonModal :type="2" :visible.sync="visibleCancel" @onCommonModalOk="handleVoucherCancel"></CommonModal>
  </a-card>
</template>
<script>
  import { sendPageInfoList, voucherCancel, voucherDelay, printDetails, exportSendPageInfoByPageId, sendPageAdd, officeLog } from '@/api/headquartersCoupon/index'
  import { STable } from '@/views/box/components'
  import { LogModal, CommonModal, RecordFilter } from './components/index'
  import Header from '@/views/box/components/layouts/Header'
  import { mapGetters } from 'vuex'
  import qs from 'qs'
  // 布尔返回”是否“
  function booleanToText(value) {
    if (value === true) {
      return '是'
    } else if (value === false) {
      return '否'
    } else {
      return ''
    }
  }
  const columns = [
    {
      title: '状态',
      width: 100,
      align: 'center',
      scopedSlots: { customRender: 'status' }
    },
    {
      title: 'AWARDID',
      width: 100,
      align: 'center',
      dataIndex: 'awardId'
    },
    // {
    //   title: '适用店铺',
    //   width: 100,
    //   align: 'center',
    //   dataIndex: 'stores'
    // },
    {
      title: '发放手机号',
      width: 200,
      align: 'center',
      dataIndex: 'mobile'
    },
    {
      title: '发放会员名',
      width: 100,
      align: 'center',
      dataIndex: 'name'
    },
    {
      title: '核销手机号',
      width: 100,
      align: 'center',
      dataIndex: 'useMobile'
    },
    {
      title: '核销会员名',
      align: 'center',
      width: 100,
      dataIndex: 'useName'
    },
    {
      title: '是否公司员工',
      align: 'center',
      width: 100,
      dataIndex: 'empIs',
      customRender: (text) => {return booleanToText(text)}
    },
    {
      title: '发放是否与核销一致',
      width: 100,
      align: 'center',
      dataIndex: 'sameIs',
      customRender: (text) => {return booleanToText(text)}
    },
    {
      title: '会员ID',
      align: 'center',
      width: 100,
      dataIndex: 'vipId'
    },
    {
      title: '核销零售单',
      width: 100,
      align: 'center',
      dataIndex: 'retailNo'
    },
    {
      title: '核销件数',
      align: 'center',
      width: 100,
      dataIndex: 'useValidNum'
    },
    {
      title: '核销总金额',
      width: 100,
      align: 'center',
      dataIndex: 'useAmount'
    },
    {
      title: '申请时间',
      width: 180,
      align: 'center',
      dataIndex: 'modifyDate'
    },
    {
      title: '券号',
      width: 150,
      align: 'center',
      dataIndex: 'vouNo'
    },
    {
      title: '券类型',
      width: 100,
      align: 'center',
      scopedSlots: { customRender: 'sendType' }
    },
    {
      title: '券面额',
      width: 100,
      align: 'center',
      dataIndex: 'vouAmount'
    },
    {
      title: '券使用余额',
      width: 100,
      align: 'center',
      dataIndex: 'noUserAmount'
    },
    {
      title: '有效期',
      width: 100,
      align: 'center',
      dataIndex: 'validDate'
    },
    {
      title: '是否核销',
      width: 100,
      align: 'center',
      dataIndex: 'isValid',
      customRender: (text) => {return booleanToText(text)}
    },
    {
      title: '核销时间',
      width: 100,
      align: 'center',
      dataIndex: 'useTime'
    },
    {
      title: '核销店铺',
      width: 100,
      align: 'center',
      dataIndex: 'useStore'
    },
    {
      title: '操作',
      width: 170,
      align: 'center',
      fixed: 'right',
      scopedSlots: { customRender: 'action' }
    }
  ]

  export default {
    components: {
      RecordFilter,
      STable,
      LogModal,
      CommonModal,
      Header
    },
    data() {
      return {
        records: [],
        voucherNo: '',
        logPagination: {
          current: 1,
          pageSize: 10,
          total: 0,
          showTotal: total => `共有 ${total} 条数据`
        },
        selectedRowKeys: [],
        logTitle: '',
        logData: [{
          id: 1
        }],
        visibleLog: false,
        visibleCancel: false,
        exportSendPageInfoByPageId,
        record: {},
        visibleDelay: false,
        details: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        columns,
        // pageSize: 10,
        paginationProps: {
          total: 0,
          showTotal: total => `共有 ${total} 条数据`
          // onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize)
        },
        queryParam: {},
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          const data = {
            pageId: this.$route.params.id,
            current: parameter.pageNo,
            size: parameter.pageSize,
            ...this.queryParam
          }
          return sendPageInfoList(data).then(res => {
            if (res.code === 200) {
              this.details = res.data
              const { records, total, current, size, pages } = res.data.userVoucherInfoIPage
              const data = {
                page: {
                  count: total,
                  pageNo: current,
                  pageSize: size,
                  pages
                },
                data: records
              }
              this.records = records
              return data
            } else {
              this.$message.error(res.msg || res.message)
              const data = {
                page: {
                  count: 0,
                  pageNo: 0,
                  pages: 0
                },
                data: []
              }
              return data
            }
          })
        }
      }
    },
    created() {
      console.log(this.userInfo(), 'userinfo')
    },
    computed: {
      rowSelection(){
        return { 
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
         }
      }
    },
    watch: {
    },
    mounted() {
    },
    methods: {
      ...mapGetters(['nickname', 'avatar', 'userInfo']),
      // 全选
      onSelectAll() {
        if (this.selectedRowKeys.length == this.records.length) {
          this.selectedRowKeys = []
        } else {
          this.selectedRowKeys = this.records.map(e => e.vouNo)
        }
      },
      // 补发
      onReissueCoupon() {
        const { 
          id,
          department,
          remarks,
          sendType} = this.details
        const data = {
          id,
          department,
          remarks,
          season: 1,
          sendType
        }
        sendPageAdd(data).then(res => {
          if (res.code == 200) {
            this.$router.push(`/headquarters-coupon/reissue/${res.data}?sendType=${this.details.sendType}&pageId=${id}`)
          } else {
            this.issueConfirmFlag = false
            this.$message.warning(res.msg || res.message)
          }
        })
      },
      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      },

      // 补发日志
      handleReissueLog() {
        this.logTitle = '批次日志记录'
        this.voucherNo = ''
        this.visibleLog = true
        this.logPagination.current = 1
        this.getOfficeLog([4])
      },

      // 打开券日志记录
      handleOpenCouponLog(voucherNo) {
        this.logTitle = '券日志记录'
        this.voucherNo = voucherNo
        this.visibleLog = true
        this.logPagination.current = 1
        this.getOfficeLog([2,3])
      },

      // 日志
      getOfficeLog(logType) {
        const data = {
          logType: logType, //1打印2作废3延迟4补发
          pageId: this.details.id,
          voucherNo: this.voucherNo ? this.voucherNo : null,
          current: this.logPagination.current,
          size: this.logPagination.pageSize
        }
        officeLog(data).then(res => {
          if (res.code === 200) {
            const { records, total } = res.data
            this.logData = records
            const pagination = { ...this.logPagination }
            pagination.total = total
            this.logPagination = pagination
          } else {
            this.$message.warning(res.msg || res.message)
          }
        })
      },

      // 日志分页
      onPageChange(v) {
        this.logPagination = v
        this.getOfficeLog()
      },

      // 作废
      handleOpenCancel(record) {
        this.record = record
        this.visibleCancel = true
      },

      // 批量优惠券作废
      handleOpenBatchCancel() {
        this.record = {vouNo: this.selectedRowKeys.join(',')}
        this.visibleCancel = true
      },

      // 作废
      handleVoucherCancel(v) {
        const {vouNo} = this.record
        if (!vouNo) {
          this.$message.info('无券号！')
          return
        }
        const data = {
          pageId: this.details.id,
          vouchersNo: vouNo,
          ...v
          // vouchersNoEnd: bigNo,
          // vouchersNoStart: smallNo
        }
        voucherCancel(data).then(res => {
          if (res.code === 200) {
            this.record = {}
            this.selectedRowKeys = []
            this.visibleCancel = false
            this.$refs.table.refresh()
          } else {
            this.$message.warning(res.msg || res.message)
          }
        })
      },

      // 延期弹窗
      handleOpenDelay(record) {
        this.record = record
        console.log(record, 'record')
        this.visibleDelay = true
      },

      // 批量延期弹窗
      handleOpenBatchDelay() {
        this.record = {vouNo: this.selectedRowKeys.join(',')}
        this.visibleDelay = true
      },

      // 延期
      handleVoucherDelay(v) {
        const {vouNo} = this.record
        if (!vouNo) {
          this.$message.info('无券号！')
          return
        }
        const data = {
          pageId: this.details.id,
          vouchersNo: vouNo,
          ...v
        }
        voucherDelay(data).then(res => {
          if (res.code === 200) {
            this.record = {}
            this.selectedRowKeys = []
            this.visibleDelay = false
            this.$refs.table.refresh()
          } else {
            this.$message.warning(res.msg || res.message)
          }
        })
      },

      // 批量优惠券补打印
      handleBatchPrint() {
        this.handlePrint({vouNo: this.selectedRowKeys.join(',')})
      },

      // 补打印
      handlePrint(record) {
        const {vouNo} = record
        if (!vouNo) {
          this.$message.info('无券号！')
          return
        }
        const data = {
          pageId: this.details.id,
          vouchersNo: vouNo
        }
        printDetails(data).then(res => {
          if (res.code === 200) {
            const data = decodeURIComponent(JSON.stringify(res.data))
            this.$router.push(`/headquarters-coupon/print/1?data=${data}`)
          } else {
            this.$message.warning(res.msg || res.message)
          }
        }).catch(err => {
        })
      },

      // 下载明细表
      handleExportSendPageInfoByPageId(v) {
        const data = {
          pageId: this.details.id,
          search: v.search
        }
        window.location.href = `${this.exportSendPageInfoByPageId}?${qs.stringify(data)}`
      },

      onSearch(obj) {
        this.queryParam = obj
        this.$refs.table.refresh(true)
      }
    }
  }
</script>
<style lang="less" scoped>
  /*/deep/ .ant-descriptions-row > td{*/
  /*  white-space: nowrap;*/
  /*  vertical-align: top;*/
  /*}*/
  /*/deep/ .ant-descriptions-item > span {*/
  /*  white-space: normal;*/
  /*  vertical-align: top;*/
  /*}*/
  .batch-operation-wrapper{
    width: 450px;
    margin: -48px 0 0 0;
  }
</style>
